package com.kun.music.controller;

import com.alibaba.fastjson.JSONObject;
import com.kun.music.domain.Rank;
import com.kun.music.service.RankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author fangkun
 * @create 2023-01-10-10:16
 */
@RestController
public class RankController {

    @Autowired
    private RankService rankService;

    @PostMapping(value = "/rank/add")
    public Object addRank(HttpServletRequest req){
        JSONObject jsonObject = new JSONObject();
        String songListId = req.getParameter("songListId").trim();
        String consumerId = req.getParameter("consumerId").trim();
        String score = req.getParameter("score").trim();

        Rank rank = new Rank();
        rank.setSongListId(Long.parseLong(songListId));
        rank.setConsumerId(Long.parseLong(consumerId));
        rank.setScore(Integer.parseInt(score));

        boolean res = rankService.addRank(rank);
        if (res){
            jsonObject.put("code", 1);
            jsonObject.put("msg", "评价成功");
            return jsonObject;
        }else {
            jsonObject.put("code", 0);
            jsonObject.put("msg", "评价失败");
            return jsonObject;
        }
    }

    @GetMapping(value = "/rank")
    public Object rankOfSongListId(@RequestParam String songListId){
        JSONObject jsonObject = new JSONObject();

        List<Rank> list = rankService.rankOfSongListId(Long.parseLong(songListId));
        int sum = 0;
        for (Rank item : list){
            sum += item.getScore();
        }
        jsonObject.put("score",sum / list.size());
        return jsonObject;
    }
}
